package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
	"tgpl/ch2/tempconv"
)

func main() {
	args := os.Args[1:]

	if len(args) > 0 {
		for _, arg := range args {
			conv(arg)
		}
	} else {
		reader := bufio.NewReader(os.Stdin)
		for {
			fmt.Print("input temperature: ")

			input, err := reader.ReadString('\n')
			if err != nil {
				fmt.Fprintf(os.Stderr, "ex2.2: %v\n", err)
				os.Exit(1)
			}

			input = strings.TrimSpace(input)
			if input == "q" {
				break
			}

			conv(input)
		}
	}
}

func conv(input string) {
	t, err := strconv.ParseFloat(input, 64)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ex2.2: %v\n", err)
		os.Exit(1)
	}
	f := tempconv.Fahrenheit(t)
	c := tempconv.Celsius(t)
	fmt.Printf(
		"%s = %s, %s = %s\n",
		f,
		tempconv.FToC(f),
		c,
		tempconv.CToF(c),
	)
}
